package test2;

/**
 * @author spf
 * @date 2024/9/6
 * @time 13:55
 */
class Slution {
    private final int totalNumbers;
    private int currentNumber = 1;
    private final Object lock = new Object();

    public Slution(int totalNumbers){
        this.totalNumbers = totalNumbers;
    }

    public void printNumbers(){
        Thread threadA = new Thread(()->{
            while(currentNumber <= totalNumbers){
                synchronized (lock){
                    if(currentNumber %2 == 1){
                        System.out.println("线程A打印：" + currentNumber);
                        currentNumber++;
                        lock.notify();
                    }else{
                        try{
                            lock.wait();
                        }catch(Exception e){
                            Thread.currentThread().interrupt();
                            break;
                        }
                    }
                }
            }

        });

        Thread threadB = new Thread(()->{
            while(currentNumber <= totalNumbers){
                synchronized (lock){
                    if(currentNumber %2 == 0){
                        System.out.println("线程B打印：" + currentNumber);
                        currentNumber++;
                        lock.notify();
                    }else{
                        try{
                            lock.wait();
                        }catch(Exception e){
                            Thread.currentThread().interrupt();
                            break;
                        }
                    }
                }
            }

        });


        threadA.start();
        threadB.start();

        try{
            threadA.join();
            threadB.join();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        Slution ap =new Slution(10);
        ap.printNumbers();
    }
}
